const base_url = ''
const httpRequest = (opts = {}, data = {}) => {
	if (!opts.url) {
		console.error('!url')
		return false
	}
	// 线上环境
	const url = base_url + opts.url
	 const token = uni.getStorageSync('token') || ''; // 从 localStorage 获取 token
	const method = opts.method || 'GET'
	const header = {
		'X-Requested-With': 'XMLHttpRequest',
		"Accept": "application/json",
		'Content-Type': 'application/json; charset=UTF-8',
		...opts.header,
		 Authorization: token // 添加 token 到 header
	}
	// 前置操作
	const httpDefaultOpts = {
		url,
		data,
		method,
		header,
		dataType: 'json'
	}
	// 后置操作
	const promise = new Promise((resolve, reject) => {
		uni.request(httpDefaultOpts).then(res => {

			const {
				code = 500, message = "网络错误，请稍后重试！"
			} = res.data || {}
			switch (code) {
				case 0:
					resolve(res.data)
					break;
				case 200:
					resolve(res.data)
					break;
				case 401:
					uni.clearStorageSync() //清除数据缓存
					reject('token过期，请重新登录!')
					uni.showToast({
						title: 'token过期，请重新登录!',
						icon: 'none'
					})
					setTimeout(()=>{
						 // window.top.location.href = 'http://192.168.31.199:5173';
						 window.top.location.href = 'https://auth.mdlvip.cn';
					},1000)
					break;
				default:
					reject(message)
					break;
			}
		}).catch(err => {
			reject(err)
		})
	})
	// #ifdef H5
		return promise.catch(err => {
			uni.showToast({
				title: err,
				icon: 'none'
			})
			throw new Error(err)
		})
	// #endif
	
	// #ifdef MP-WEIXIN
		return promise
	// #endif

}
export default httpRequest
